<template>
    <view class="container">
        <custom-nav-bar title="露营地预订与攻略平台" :show-back="false" />
        <view class="content">
            <!-- 1.0 搜索区域 -->
            <view class="search-section">
                <view class="search-box">
                    <text class="search-icon">🔍</text>
                    <input class="search-input" type="text" v-model="searchKey" placeholder="搜索营地名称"
                        @input="onSearch" />
                </view>
            </view>

            <!-- 2.0 预订状态分类 -->
            <view class="status-section">
                <view class="status-item" v-for="item in statusList" :key="item.id"
                    :class="{ 'active': currentStatus === item.id }" @tap="switchStatus(item)">
                    <text>{{ item.name }}</text>
                </view>
            </view>

            <!-- 3.0 营地预订列表 -->
            <scroll-view class="booking-section" scroll-y>
                <view class="booking-list">
                    <view class="booking-item" v-for="camp in filteredBookings" :key="camp.id">
                        <image :src="camp.image" mode="aspectFill" class="camp-image" />
                        <view class="camp-info">
                            <text class="camp-name">{{ camp.name }}</text>
                            <view class="camp-meta">
                                <text class="camp-address">{{ camp.address }}</text>
                                <text class="camp-status" :class="camp.status">{{ camp.statusText }}</text>
                            </view>
                            <view class="price-action">
                                <view class="price-info">
                                    <text class="price">¥{{ camp.price }}</text>
                                    <text class="price-label">/天</text>
                                </view>
                                <!-- 根据不同状态显示不同按钮 -->
                                <view class="action-btns">
                                    <button v-if="camp.status === 'pending'" class="action-btn pay-btn"
                                        @tap.stop="onPayTap(camp)">支付</button>
                                    <button v-if="camp.status === 'pending'" class="action-btn cancel-btn"
                                        @tap.stop="onCancelTap(camp)">取消</button>
                                    <button v-if="camp.status === 'paid'" class="action-btn complete-btn"
                                        @tap.stop="onCompleteTap(camp)">完成</button>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { orderApi } from '@/api/index'
import CustomNavBar from '@/components/custom-nav-bar/custom-nav-bar.vue'


const searchKey = ref('')
const currentStatus = ref(0)

const statusList = [
    { id: 0, name: '全部' },
    { id: 1, name: '待支付' },
    { id: 2, name: '已支付' },
    { id: 3, name: '已完成' },
    { id: 4, name: '已取消' }
]
const bookingList = ref([])

// 加载预订列表
const loadBookingList = async () => {
    const userInfo = uni.getStorageSync('userInfo')
    if (!userInfo || !userInfo.id) {
        bookingList.value = []
        uni.showToast({
            title: '请先登录',
            icon: 'none'
        })
        return
    }

    try {
        // 直接传递 userId 字符串值，而不是对象
        const res = await orderApi.getOrderList(userInfo.id)
        if (Array.isArray(res.data)) {
            // 新订单排最前
            bookingList.value = res.data.reverse().map(item => {
                // 状态映射
                let status = item.booking_status || item.status || 'pending'
                let statusText = ''
                switch (status) {
                    case 'pending': statusText = '待支付'; break;
                    case 'paid': statusText = '已支付'; break;
                    case 'completed': statusText = '已完成'; break;
                    case 'cancelled': statusText = '已取消'; break;
                    default: statusText = '未知';
                }
                return {
                    ...item,
                    status,
                    statusText,
                    image: item.image_url || item.image // 兼容图片字段
                }
            })
        }
    } catch (error) {
        uni.showToast({
            title: '加载预订列表失败',
            icon: 'none'
        })
    }
}

// 支付操作
const onPayTap = async (camp) => {
    const userInfo = uni.getStorageSync('userInfo')
    try {
        await orderApi.handlePayment(camp.id, userInfo.id)
        uni.showToast({
            title: '支付成功',
            icon: 'success'
        })
        // 刷新列表
        loadBookingList()
    } catch (error) {
        console.error('支付失败:', error)
        uni.showToast({
            title: '支付失败',
            icon: 'none'
        })
    }
}

// 取消预订
const onCancelTap = async (camp) => {
    const userInfo = uni.getStorageSync('userInfo')
    try {
        await orderApi.cancelOrder(camp.id, userInfo.id)
        uni.showToast({
            title: '取消成功',
            icon: 'success'
        })
        // 刷新列表
        loadBookingList()
    } catch (error) {
        console.error('取消失败:', error)
        uni.showToast({
            title: '取消失败',
            icon: 'none'
        })
    }
}

// 完成预订
const onCompleteTap = async (camp) => {
    const userInfo = uni.getStorageSync('userInfo')
    try {
        await orderApi.completeOrder(camp.id, userInfo.id)
        uni.showToast({
            title: '已完成预订',
            icon: 'success'
        })
        // 刷新列表
        loadBookingList()
    } catch (error) {
        console.error('操作失败:', error)
        uni.showToast({
            title: '操作失败',
            icon: 'none'
        })
    }
}

// 切换状态
const switchStatus = (item) => {
    currentStatus.value = item.id
}

// 搜索功能
const onSearch = () => {
    // 重置状态为"全部"，这样可以在所有订单中搜索
    currentStatus.value = 0
}

// 根据搜索关键词和当前状态筛选预订列表
const filteredBookings = computed(() => {
    let result = bookingList.value

    // 按状态筛选
    if (currentStatus.value !== 0) {
        const statusMap = {
            1: 'pending',
            2: 'paid',
            3: 'completed',
            4: 'cancelled'
        }
        result = result.filter(item => item.status === statusMap[currentStatus.value])
    }

    // 按关键词搜索
    if (searchKey.value.trim()) {
        const key = searchKey.value.trim().toLowerCase()
        result = result.filter(item => {
            return (
                // 使用实际的字段名
                (item.name && item.name.toLowerCase().includes(key)) ||         // 营地名称
                (item.address && item.address.toLowerCase().includes(key)) ||   // 地址
                (item.price && item.price.toString().includes(key)) ||         // 价格
                (item.statusText && item.statusText.toLowerCase().includes(key)) || // 状态文本
                (item.bookingDate && item.bookingDate.includes(key))           // 预订日期
            )
        })
    }

    console.log('搜索关键词:', searchKey.value)
    console.log('筛选结果:', result)

    return result
})

onShow(() => {
    loadBookingList()
})

onMounted(() => {
    loadBookingList()
})
</script>

<style>
/* 状态分类样式 */
.status-section {
    display: flex;
    background: #fff;
    padding: 20rpx;
    border-bottom: 1rpx solid #eee;
}

/* 搜索区域样式 */
.search-section {
    background: #f5f5f5;
    padding: 20rpx;
}

.search-box {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 36rpx;
    padding: 10rpx;
}

.search-icon {
    color: #999;
    margin-right: 10rpx;
}

.search-input {
    flex: 1;
    border: none;
    height: 100%;
    font-size: 28rpx;
}

.status-item {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 10rpx 0;
    position: relative;
}

.status-item.active {
    color: #409eff;
    font-weight: bold;
}

.status-item.active::after {
    content: '';
    position: absolute;
    bottom: -10rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background: #409eff;
    border-radius: 2rpx;
}

/* 预订列表样式 */
.booking-section {
    height: calc(100vh - 200rpx);
}

.booking-list {
    padding: 20rpx;
}

.booking-item {
    margin-bottom: 20rpx;
    background: #fff;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.camp-image {
    width: 100%;
    height: 300rpx;
}

.camp-info {
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.camp-name {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.camp-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.camp-address {
    font-size: 24rpx;
    color: #999;
}

.camp-status {
    padding: 4rpx 12rpx;
    border-radius: 4rpx;
    font-size: 24rpx;
}

.pending {
    color: #e6a23c;
    background: #fdf6ec;
}

.paid {
    color: #409eff;
    background: #ecf5ff;
}

.completed {
    color: #67c23a;
    background: #f0f9eb;
}

.cancelled {
    color: #909399;
    background: #f4f4f5;
}

.price-action {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;
}

.price-info {
    display: flex;
    align-items: baseline;
}

.price {
    font-size: 36rpx;
    color: #f56c6c;
    font-weight: bold;
}

.price-label {
    font-size: 24rpx;
    color: #999;
    margin-left: 5rpx;
}

.action-btns {
    display: flex;
    gap: 10rpx;
}

.action-btn {
    padding: 10rpx 20rpx;
    border-radius: 6rpx;
    font-size: 24rpx;
    color: #fff;
    border: none;
}

.pay-btn {
    background: #409eff;
}

.cancel-btn {
    background: #f56c6c;
}

.complete-btn {
    background: #67c23a;
}

.content {
    margin-top: 100rpx;
}
</style>